﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_UserId_FormItem"
							prop="Entity.UserId"
							label="用户"
							:rules="[{ required: true, message: '用户为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.UserId" clearable class="width100" :disabled="!!passedRowData">
								<el-option v-for="item in stateData.AllFrameworkUsers" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_GroupId_FormItem"
							prop="Entity.GroupId"
							label="部门"
							:rules="[{ required: true, message: '部门为必填项', trigger: 'blur' }]"
						>
							<el-cascader
								:options="stateData.AllFrameworkGroups"
								:props="{ checkStrictly: true, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
								clearable
								filterable
								class="w100"
								v-model="stateData.vmModel.Entity.GroupId"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_JobPositionId_FormItem"
							prop="Entity.JobPositionId"
							label="岗位"
							:rules="[{ required: true, message: '岗位为必填项', trigger: 'blur' }]"
						>
							<el-select
								v-model="stateData.vmModel.Entity.JobPositionId"
								clearable
								class="width100"
								placeholder="请先选择部门"
								:disabled="!stateData.vmModel.Entity.GroupId"
							>
								<el-option v-for="item in stateData.AllSysJobPositions" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_IsMain_FormItem"
							prop="Entity.IsMain"
							label="是否主岗"
							:rules="[{ required: true, message: '是否主岗为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.IsMain" clearable class="width100">
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, watch, nextTick } from 'vue';
import { SysUserJobPositionApi as api } from '/@/views/_admin/sysuserjobposition/api';
import other from '/@/utils/other';
import { ISysUserJobPositionVm } from '/@/views/_admin/sysuserjobposition/api/interface';
import { IViewModel } from '/@/types/common';

// 定义变量内容
const ci = getCurrentInstance() as any;
const loading = ref(false);
const formRef = ref();
const passedRowData = ref<any>(null);
const stateData = reactive<IViewModel<ISysUserJobPositionVm>>({
	vmModel: {
		Entity: {
			UserId: null,
			JobPositionId: null,
			IsMain: false,
			GroupId: null,
		},
	},

	AllFrameworkUsers: [] as any[],
	AllSysJobPositions: [] as any[],
	AllFrameworkGroups: [] as any[],
});

// 获取岗位数据的方法
const getSysJobPositions = (groupId?: string) => {
	const url = groupId ? `/api/SysUserJobPosition/GetSysJobPositions?groupId=${groupId}` : '/api/SysUserJobPosition/GetSysJobPositions';
	return other.getSelectList(url, [], false).then((x) => {
		stateData.AllSysJobPositions = x;
	});
};

// 监听部门选择变化
watch(
	() => stateData.vmModel.Entity.GroupId,
	(newGroupId) => {
		if (newGroupId) {
			// 清空当前选择的岗位
			stateData.vmModel.Entity.JobPositionId = null;
			// 根据选择的部门获取对应的岗位
			getSysJobPositions(newGroupId);
		} else {
			// 如果没有选择部门，清空岗位数据
			stateData.AllSysJobPositions = [];
			stateData.vmModel.Entity.JobPositionId = null;
		}
	}
);

// 取消
const onClose = () => {
	closeDialog();
};

// 提交
const onSubmit = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			api()
				.add(stateData.vmModel)
				.then(() => {
					ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
					emit('refresh');
					closeDialog();
				})
				.catch((error) => {
					other.setFormError(ci, error);
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	// 检查是否有传递的行数据
	if (ci.attrs['wtmdata']) {
		passedRowData.value = ci.attrs['wtmdata'];
		// 如果传递了行数据，设置用户ID并禁用用户选择
		if (passedRowData.value.UserId) {
			stateData.vmModel.Entity.UserId = passedRowData.value.UserId;
		}
		// 如果传递了部门ID，也设置部门
		if (passedRowData.value.GroupId) {
			stateData.vmModel.Entity.GroupId = passedRowData.value.GroupId;
		}
	}

	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysUserJobPosition/GetFrameworkUsers', [], false).then((x) => {
			stateData.AllFrameworkUsers = x;
		}),
		other.getSelectList('/api/common/GetGroups?auth=false', [], false).then((x) => {
			stateData.AllFrameworkGroups = x;
		}),
		// 初始化时不加载岗位数据，等用户选择部门后再加载
	];

	// 如果有传递的部门ID，提前加载对应的岗位数据
	if (passedRowData.value?.GroupId) {
		promises.push(getSysJobPositions(passedRowData.value.GroupId));
	}

	Promise.allSettled(promises).finally(() => {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	});
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);
// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: ci.proxy.$t('message._system.common.vm.submit'),
			type: 'primary',
			onClick: onSubmit,
			visible: true,
		},
		{
			text: ci.proxy.$t('message._system.common.vm.cancel'),
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
